
;(function(){
	function getId(id){
		return document.getElementById(id);
	} 
	function getParam(str){
		var p1=str.split("?");
		if(p1.length){
			var p2=p1[p1.length-1];
			if(p2){
				var p3=p2.split("&");
				if(p3.length){
					var data={};
					for(var i=0;i<p3.length;i++){
						var p=p3[i].split("=");
						data[p[0]]=p[1];
					}
					return data;
				}
			}
		}
		return "";
	}
	function ajax(opt){
		opt = opt || {};
		opt.method = opt.method.toUpperCase() || 'POST';
		opt.url = opt.url || '';
		opt.async = opt.async;
		opt.data = opt.data || null;
		opt.success = opt.success || function () {};
		var xmlHttp = null;
		if (XMLHttpRequest) {
			xmlHttp = new XMLHttpRequest();
		}else {
			xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
		}
		var params = [];
		for (var key in opt.data){
			params.push(key + '=' + encodeURIComponent(opt.data[key]));
		}
		var postData = params.join('&');
		if (opt.method.toUpperCase() === 'POST') {
			xmlHttp.open(opt.method, opt.url, opt.async);
			xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			if(opt.token&&opt.token.key && opt.token.val) xmlHttp.setRequestHeader(opt.token.key,opt.token.val);
			xmlHttp.send(postData);
		}
		else if (opt.method.toUpperCase() === 'GET') {
			xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
			if(opt.token&&opt.token.key && opt.token.val) xmlHttp.setRequestHeader(opt.token.key,opt.token.val);
			xmlHttp.send(null);
		} 
		if(opt.async){
			xmlHttp.onreadystatechange = function () {
				if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
					opt.success(xmlHttp.responseText);
				}
			};
		}else{
			if(xmlHttp.status == 200){
				opt.success(xmlHttp.responseText);
			}
		}

	}
    
    var player=null;
    var data=getParam(location.search);
    var id="";
    var title="";
    var thumb="";
    var videoId="";//当前播放的视频id
    var type="";//type=4是录像视频
    //获取视频
    if(data&&data.id){
        id=data.id;  // 视频id 
        type=data.type;
        videoId=data.id; 
        ajax({
            method: 'GET',
            async:true,
            url: "/barrage/getArticleDetial",
            data:{id:id,categoryId:type||2},
            success: function (res) {
                var res=JSON.parse(res);
                if(res.status==200){
                    var data=res.data;
                    title=data.title;
                    thumb=data.thumb
                    getId("title").innerText=data.title || "";
                    getId("name").innerText=data.author || "";
                    getId("playCount").innerText=data.viewCount || 0;
                    getId("eggCount").innerText=data.ticketCount || 0;
                    var svideo=data.subsectionVideo;
                    var videoUrl=type==4?svideo[0].videoUrl:data.videoUrl;
                    getId("videoWrap").innerHTML='<video id="video" class="video-js vjs-default-skin" preload="auto" controls poster=""><source id="videoSource" src="'+videoUrl+'" type="application/x-mpegURL"/></video>';
                    if(type==4){
                        var str="";
                        if(svideo.length>1){
                            for(var i=0;i<svideo.length;i++){
                                var active=i==0?"active":"";
                                str+='<li data-url="'+svideo[i].videoUrl+'" data-id="'+svideo[i].id+'" class="'+active+'" title="'+svideo[i].title+'"><span class="title">'+svideo[i].title+'</span></li>';
                            }
                            $(".play-danmu-pieces").html(str);
                            videoId=svideo[0].id;
                        }
                    }
                    player=videojs("video",{poster:data.thumb,width:"1000",height:"562.5"},function(){
                        ready();
                    });
                    
                }else{
                    getId("videoWrap").innerHTML="<div style='text-align:center;line-height:550px;color:#ccc;'>获取视频失败</div>" 
                }
                
            }
        });
    }
    
    function ready(){        
		player.volume(0.66);//设置音量0~1
        //初始化弹幕
        $("#danmu").danmu({
            height: 500,  //弹幕区高度
            width: 1000,   //弹幕区宽度
            zindex :100,   //弹幕区域z-index属性
            speed:8000,      //滚动弹幕的默认速度，这是数值值得是弹幕滚过每672像素所需要的时间（毫秒）
            sumTime:65535,   //弹幕流的总时间
            danmuLoop:false,   //是否循环播放弹幕
            defaultFontColor:"#FFFFFF",   //弹幕的默认颜色
            fontSizeSmall:20,     //小弹幕的字号大小
            FontSizeBig:24,       //大弹幕的字号大小
            opacity:"0.9",			//默认弹幕透明度
            topBottonDanmuTime:6000,   // 顶部底部弹幕持续时间（毫秒）
            SubtitleProtection:true,     //是否字幕保护
            positionOptimize:true,         //是否位置优化，位置优化是指像AB站那样弹幕主要漂浮于区域上半部分
        });
        
        player.on('pause',function(e) {
            $('#danmu').danmu('danmuPause'); 
            clear();
        });
        player.on('play',function(e) {
            getId("danmuWrap").style.display="block";
            
            $('#danmu').danmu('danmuResume');
            playDanmu();
                 
        });
        player.on('ended',function(e) {
            $('#danmu').danmu('danmuStop');
            isReplay=true;
            clear();
        });
    }
    $(".play-danmu-pieces").on("click","li",function(){
        if($(this).hasClass("active")) return;
        $(this).addClass("active").siblings().removeClass("active");
        videoId=$(this).data("id");
        var url=$(this).data("url");
        var marks=$(this).data("marks");
        currentMark=marks;
        player.src({type: "application/x-mpegURL", src: url });  
        $("#danmu").data("danmuList",{});//清除原有弹幕
        $('#danmu').danmu('danmuStop');
         
        initDanmu();
        player.play(); 
    });
    var timer=null;
    var baseTime=0;
    var isReplay=false;
    var isNew=true;
    var requestTime=0;
    function playDanmu(){
        var currentTime = player.currentTime();
        var ti=$('#danmu').data("nowTime")-currentTime*10>15;
        var tj=currentTime*10-$('#danmu').data("nowTime")>30;
        if(ti || tj){
            $('#danmu').danmu("setTime",parseInt(currentTime*10));
            $('#danmu').danmu('danmuStart'); 
        }
        if(baseTime-currentTime>=0&&currentTime<0.5&&ti) isReplay=true;
        if(currentTime-baseTime>60 || currentTime<0.3){
            if(!isReplay&&isNew){
                $('#danmu').danmu("setTime",parseInt(currentTime*10));
                getDanmu(parseInt(Math.ceil(player.currentTime()/60))||1);
                isNew=false;
            }else if(!isReplay){
                $('#danmu').danmu("setTime",parseInt(currentTime*10));
                getDanmu(parseInt(Math.ceil(player.currentTime()/60))||1);
            }
            $('#danmu').danmu('danmuStart'); 
            baseTime=currentTime;
        }
        timer = setTimeout(playDanmu,1000);
    }
    function initDanmu(){
        clear();
        timer=null;
        baseTime=0;
        isReplay=false;
        isNew=true;
        requestTime=0;
    }
    //清除定时器
    function clear(){
        if(timer){
            clearTimeout(timer);
            timer = null;
        }
    }
    function getDanmu(time){
        if(requestTime==time) return;//防止重复请求弹幕
        ajax({
            method: 'POST',
            async:false,
            url: "/barrage/getBarrage",
            data:{videoId:videoId,minuteTime:time},
            success: function (res) {
                var res=JSON.parse(res);
                if(res.status==200){
                    requestTime=time;
                    var list=res.data.list;
                    var array=[];
                    for(var i=0;i<list.length;i++){
                        var time=Math.ceil(list[i].videoTime/100);
                        var content=list[i].content;
                        var color=list[i].color;
                        array.push({"text":content, "color":color ,"size":"0","position":"0","time":time});
                    }
                    $('#danmu').danmu('addDanmu',array);
                }else{
                    
                }
                
            }
        });
    }
	//发送弹幕
    function sendDanmu(){
        var videoTime=player.currentTime() || 0.1;
        var content=getId("content").value;
        if(content.length>25){
            getId("danmuTip").style.display="block";
            setTimeout(function(){
                getId("danmuTip").style.display="none";
            },2000);
        }
        if(content&&content.length<=25){
            $('#danmu').danmu("setOpacity",1);
            $('#danmu').danmu("addDanmu",{"text":content, "color":"#fff" ,"size":"1","position":"0","time":$('#danmu').data("nowTime")+5,"isnew":" "}); 
            getId("content").value="";
            ajax({
                method: 'POST',
                async:true,
                //token:{key:"Authorization",val:"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MDkwMDA4NjYsImp0aSI6IlQxSWh1VHViRFVFcVB0XC94OGRpM3pxVUJWRFAwRzd5MnRNaXdmM1RZUGFzPSIsImlzcyI6ImFwaS53d3cuZ2pnai5jb20iLCJuYmYiOjE1MDkwMDA4NjcsImV4cCI6MTUwOTAwMDg3NywiaWQiOiI0NSIsInVzZXJuYW1lIjoiMTc3Mjc1NTQzNjUiLCJwYXNzd29yZCI6ImUxMGFkYzM5NDliYTU5YWJiZTU2ZTA1N2YyMGY4ODNlIn0.PR6nrnAlmzHf7p6PEPsrsYEwPUznCgc7sDVdZs6XidU"},
                url: "/barrage/sendBarrage",
                data:{videoId:videoId,videoTime:videoTime*1000,content:content},
                success: function (res) {
                    var res=JSON.parse(res);
                    if(res.status==1){
                        
                    }else{
                        
                    }
                    
                }
            });
        }
        
    }
    getId("play").addEventListener("click",function(e){
        if(e.target.id=="danmu"){ 
            if(player.paused()){
                player.play();
            }else{
                player.pause();
            }
        }
		if(e.target.id=="sendDanmu"){
            getId("danmuWrap").style.display="block";
            if(getId("sendDanmu").className.indexOf("play-disabled")!=-1){
                document.getElementsByClassName("header-login-wrap")[0].style.display="block";
                return;
            }
            sendDanmu();
        }
        if(e.target.className.indexOf("vjs-fullscreen-control")!=-1){
            setTimeout(function(){
                if(getId("video").className.indexOf("vjs-fullscreen")!=-1){
                    getId("danmuWrap").className="play-danmu-show play-danmu-fullscreen";
                }else{
                    getId("danmuWrap").className="play-danmu-show";
                }
            },500);
            
        }
    });
    getId("content").addEventListener("keypress",function(e){
        if(event.keyCode == 13){
            getId("danmuWrap").style.display="block";
            if(getId("sendDanmu").className.indexOf("play-disabled")!=-1){
                document.getElementsByClassName("header-login-wrap")[0].style.display="block";
                return;
            }
            sendDanmu();
        }
    })
    
    
})();